<template>
  <div class="autoDetail">
    <h1 class="back-title"><i @click="$router.go(-1)" class="iconfont icon-fanhui"></i>{{!id?'添加新的':'编辑'}}社交模板</h1>
    <el-form ref="form" :model="form" label-width="90px" label-position="left" :rules="rules">
      <el-form-item label="模块名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入社交模块名称" maxlength="20" size="small"
                  style="width:260px"></el-input>
      </el-form-item>
      <el-form-item label="是否共享:" prop="isShare">
        <el-radio v-model="form.isShare" :label="true">是</el-radio>
        <el-radio v-model="form.isShare" :label="false">否</el-radio>
      </el-form-item>
      <el-form-item label="当前账户:" prop="isShare">
        <img :src="userInfo.avatar" alt="" class="my-head">
      </el-form-item>
      <el-form-item label="发布内容:" prop="content">
        <el-input v-model="form.content" placeholder="请输入发布内容" type="textarea" :rows="7" maxlength="144" show-word-limit
                  style="width: 600px"></el-input>
      </el-form-item>
      <el-form-item>
        <p class="message-xml">(提示：图片支持.jpg .jpeg .png；视频支持.mp4 .ogg .webm格式)</p>
        <div class="else-detail">
          <div class="one" v-for="(item,index) in fileList" :key="index">
            <span v-if="dealSrc(item.fileGuid)">
            <img :src="item.fileGuid" alt="">
            </span>
            <video :src="item.fileGuid" controls v-else style="display:inline-block;width:75px;height: 75px"></video>
            <div class="desc">
              <a :href="item.fileGuid" target="_blank">
                <el-button size="small" type="text">预览</el-button>
              </a>
              <el-button size="small" type="text" @click="delRow(index)">删除</el-button>
            </div>
          </div>
          <div class="two" title="添加图片或视频" v-show="form.photos.length==0&&form.video==''" @click="showLocal">
            <i class="iconfont icon-zhaopian"></i>
            <p>图片/视频</p>
          </div>
          <div class="two" title="添加图片" v-show="form.photos.length>0&&form.photos.length<4" @click="showLocal">
            <i class="iconfont icon-zhaopian"></i>
            <p>添加图片</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item class="common-btn">
        <el-button size="small" @click="$router.go(-1)">取 消</el-button>
        <el-button  size="small" type="primary" @click="submit('form')" id="submitSocial" :loading="isSave">{{isSave?'保存中':'确 定'}}</el-button>
      </el-form-item>
    </el-form>
    <!-- 弹框-->
    <el-dialog :close-on-click-modal="false"
               :close-on-press-escape='false'
               :visible.sync="dialogVisible" width="600px" title="选择文件" center>
      <div class="line-local">
        <span>本地上传：</span>
        <div class="else-local">
          <el-upload ref="uploadResource"
                     class="upload-demo"
                     action=""
                     :accept="accept"
                     :http-request="uploadFile"
                     :before-upload="beforeUpload"
                     :show-file-list=false
                     :multiple=false>
            <el-button size="medium" :loading="loading">{{loading?'上传中':'浏览'}}</el-button>
          </el-upload>
        </div>
      </div>
      <div class="line-local">
        <span>云盘上传：</span>
        <el-button size="medium" @click="chooseCloud" :loading="isLoad">{{isLoad?'载入中':'选择'}}</el-button>
      </div>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="dialogVisible=false">确 定</el-button>
      </div>
      <!-- 上传信息结果展示-->
      <a v-for="item,index in fileList" :key="index" href="javascript:void(0)" class="el-upload-list__item-name">
        <a class="more text" target="_blank" :href="item.fileGuid"><i class="el-icon-document"></i>{{item.picName}}</a>
        <i class="el-icon-close" title="删除" @click="fileList.splice(index,1)"></i>
      </a>
    </el-dialog>
    <!--    云盘选择-->
    <CloundUp ref="cloundUp" @setFile="setFile" ></CloundUp>
    <VueTour ref="vueTour" :steps="steps"
             prev="/automation/template/xml" type="0" path="/automation/socialAutomation"></VueTour>
  </div>
</template>

<script>
    import {xmlTemplateDetail, editXmlTemplate, saveXml} from "@/api/automation/xml"
    import CloundUp from '@/components/product/DialogColund'
    import {mapGetters, mapState} from 'vuex'
    import VueTour from '@/components/automation/VueRour'
    import {uploadOss} from '@/util/file'

    export default {
        name: "addXml",
        components: {VueTour, CloundUp},
        data() {
            return {
                dialogVisible: false,
                isWater: '1',
                form: {
                    name: '',
                    content: '',
                    photos: [],
                    video: '',
                    isShare: false
                },
                rules: {
                    name: [
                        {required: true, message: '请输入社交模块名称', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '请添加发布内容', trigger: 'blur'},
                        {min: 0, max: 144, message: '长度在 1 到 144 个字符', trigger: 'blur'}
                    ],
                    isShare: [
                        {required: true, message: '请选择是否共享', trigger: 'blur'},
                    ]
                },
                id: '',
                header: {},
                fileList: [],
                steps: [
                    {
                        target: '#submitSocial',
                        content: '【社交自动化规则创建】<br>第二步，点击保存按钮完成社交模板创建'
                    }
                ],
                // accept: 'image/png,image/jpeg,image/jpg',
                accept: 'image/png,image/jpeg,image/jpg,video/mp4,video/webm,application/ogg, audio/ogg',
                loading: false,
                isLoad: false,
                isSave: false
            }
        },
        watch: {
            fileList(val) {
                if (val.length == 0) {
                    // this.accept = 'image/png, image/jpeg, image/jpg';
                    this.accept = 'image/png, image/jpeg, image/jpg,video/mp4,video/webm,application/ogg, audio/ogg';
                    return;
                }
                //判断是图片还是视频
                this.getImgVideo();
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(['userInfo'])
        },
        mounted() {
            if (this.common.isFirstSocial) {
                this.$nextTick(() => {
                    this.$refs.vueTour.init();//初始化
                })
            }
            if(this.$route.path.indexOf('add')==-1){
                this.id= this.$route.params.id;
                this.getData();
            }
        },
        methods: {
            submit(formName) {
                //转换fileList
                this.getImgVideo();
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.isSave = true;
                        if (!this.id) {//新增
                            saveXml(this.form).then(res => {
                                this.dealEnd(res);
                            }).catch(() => {
                                this.isSave = false
                            })
                        } else {//编辑
                            editXmlTemplate(this.id, this.form).then(res => {
                                this.dealEnd(res);
                            }).catch(() => {
                                this.isSave = false
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            //开始上传
            uploadFile(File) {
                this.loading = true;
                let file = File.file;
                uploadOss(file).then(result => {
                    this.loading = false;
                    if (result.hasOwnProperty('url')) {
                        this.dealType([
                            {
                                fileUrl: result.url,
                                fileSize: file.size,
                                fileName: result.name + "." + file.name.split(".")[1]
                            }
                        ]);
                    } else {
                        this.$message({
                            type: "success",
                            message: '文件上传失败,请重新上传!'
                        })
                    }
                })
            },
            getImgVideo() {
                let imgType = ['.jpg', '.jpeg', '.png'];
                let videoType = ['.mp4', '.webm', '.ogg'];
                this.form.photos = [];
                this.form.video = '';
                if (this.fileList.length == 0) return;
                this.fileList.map(items => {
                    let fileGuid = items.fileGuid;
                    //区分
                    let index = fileGuid.lastIndexOf(".");
                    let fileName = "." + fileGuid.substr(index + 1);
                    fileName = fileName.split('?')[0];
                    if (imgType.includes(fileName)) {
                        this.form.photos.push(fileGuid)
                    } else if (videoType.includes(fileName)) {
                        this.form.video = fileGuid;
                    }
                })
            },
            //获取详情
            getData() {
                xmlTemplateDetail(this.$route.params.id).then(res => {
                    if (res.data.success) {
                        const result = res.data.data;
                        this.form = result;
                        if (result.photos.length > 0) {
                            result.photos.map((item, index) => {
                                this.fileList.push({
                                    fileGuid: item,
                                    fileSize: '-',
                                    picName: `图片${index + 1}`
                                })
                            })
                            this.accept = 'image/png, image/jpeg, image/jpg';
                        }
                        if (result.video != '') {
                            this.fileList.push({
                                fileGuid: result.video,
                                fileSize: '-',
                                picName: '-'
                            })
                        }
                    }
                })
            },
            delRow(index) {
                this.fileList.splice(index, 1);
                this.form.photos = [];
                this.form.video = '';
            },
            chooseCloud() {
                this.$refs.cloundUp.init({
                    maxNum:1,
                    accept:'jpg,png,jpeg,mp4,webm,ogg'
                });
            },
            //云盘选择结果
            setFile(type, fileList) {
                this.dealType(fileList);
                this.dialogVisible = false;
            },
            dealType(result) {
                let name = result[0].fileName;
                let i = name.lastIndexOf(".");
                name = "." + name.substr(i + 1);
                let videoType = ['.mp4', '.webm', '.ogg'], index = -1;
                videoType.map(item => {
                    if (name.indexOf(item) != -1) {//找到了 - 视频
                        index = 1;
                        this.form.photos = [];
                        this.fileList = [];
                    }
                })
                //判断第一次传得是什么 - 图片 还是视频
                if (index != -1) { //视频
                    this.successUp(result, 15728640, index);
                } else {//图片
                    this.successUp(result, 6291456, index);
                }
            },
            //本地上传
            showLocal() {
                if (this.$refs.uploadResource) {
                    this.$refs.uploadResource.clearFiles();
                }
                this.isLoad = false;
                this.dialogVisible = true;
            },
            dealSrc(src) {
                let imgType = ['.jpg', '.jpeg', '.png'];
                let has = false;
                imgType.map(item => {
                    if (src.indexOf(item) != -1) {
                        has = true;
                        return;
                    }
                })
                return has; //临时地址
            },
            dealEnd(res) {
                this.isSave = false;
                if (res.data.success) {
                    this.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    this.$router.go(-1)
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }

            },
            beforeUpload(file) {
                if (file.type.indexOf('image') != -1) {//图片
                    if (file.size > 6291456) {//不可上传
                        this.$message({
                            message: '单个图片最大5M，单个视频最大15M，请重新上传',
                            type: "success"
                        });
                        return false;
                    }
                } else {
                    if (file.size > 15728640) {//不可上传
                        this.$message({
                            message: '单个图片最大5M，单个视频最大15M，请重新上传',
                            type: "success"
                        });
                        return false;
                    }
                }
            },
            successUp(result, fileSize, index) {
                let resultSize = result[0].fileSize;
                resultSize = resultSize.toString();
                // let index = name.lastIndexOf(".");
                // let fileName = "."+name.substr(index+1);
                //云盘选择结果单独处理 B KB MB
                if (resultSize.indexOf('KB') != -1) {
                    let index = resultSize.lastIndexOf(".");
                    let extraSize = resultSize.substr(index + 1) != 'KB' ? 1 : 0;
                    resultSize = resultSize.substr(0, index);
                    resultSize = resultSize * 1024 + extraSize;
                } else if (resultSize.indexOf('MB') != -1) {
                    let index = resultSize.lastIndexOf(".");
                    let extraSize = resultSize.substr(index + 1) != 'MB' ? 1 : 0;
                    resultSize = resultSize.substr(0, index);
                    if (resultSize.substr(index + 1) != 'MB') {
                        extraSize = 1
                    }
                    resultSize = resultSize * 1024 * 1024;
                }
                if (resultSize > fileSize) {//不可上传
                    this.$message({
                        message: '单个图片最大5M，单个视频最大15M，请重新上传',
                        type: "success"
                    });
                } else {
                    if (index != -1) { //视频
                        this.accept = "video/mp4,video/webm,application/ogg, audio/ogg"
                    } else {
                        this.accept = 'image/png, image/jpeg, image/jpg';
                    }
                    this.fileList.push({
                        fileGuid: result[0].fileUrl,
                        fileSize: result[0].fileSize,
                        picName: result[0].fileName
                    })
                }
            },
        }
    }
</script>

<style scoped lang="scss">
  .autoDetail {
    .message-xml {
      font-size: 12px;
      color: #8c8c8c;
      line-height: 20px;
    }

    i.iconfont.icon-fanhui {
      font-size: 22px;
      color: #2A97F9;
      cursor: pointer;
    }

    .my-head {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      border: 1px solid #ddd
    }

    .else-detail {
      display: flex;
      flex-wrap: wrap;

      .one {
        display: flex;
        align-items: flex-end;
        margin-right: 15px;

        span {
          display: flex;
          align-items: center;
          width: 75px;
          height: 75px;

          img {
            width: 100%;
            vertical-align: middle;
            margin-right: 5px;
          }
        }

        .desc {
          width: 100px;
          padding-left: 5px;

          h1 {
            font-size: 14px;
            color: #000;
          }

          p {
            line-height: 10px;
            font-size: 13px;
          }

          .el-button--text {
            color: #409EFF;
            background: 0 0;
            border-bottom: 1px solid #409EFF;
            border-radius: 0;
            padding: 3px 0;
            margin-right: 10px;
          }
        }
      }
    }

    a.el-upload-list__item-name {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 26px;
      font-size: 15px;
      color: #666;
      width: 60%;

      .text {
        width: 60%;
      }

      i.el-icon-close {
        margin-left: 16px;
      }
    }
    .line-local {
      display: flex;
      align-items: center;
      width: 80%;
      margin: 24px auto;

      .else-local {
        display: flex;
        align-items: center;
        height: 60px;

        button.el-button.el-button--default.el-button--medium {
          margin-right: 20px;
        }

        p {
          margin-right: 15px !important;
          font-size: 13px;
        }
      }
    }

    .two {
      text-align: center;
      margin-right: 42px;
      cursor: pointer;
      margin-top: 11px;

      i {
        font-size: 20px;
      }

      p {
        color: #666;
        font-size: 12px;
        line-height: 10px;
      }
    }
  }
</style>
